import React, {
    Component
} from "react";
import {
    Modal,
    Tooltip,
    Form,
    Table,
    Row,
    Col,
    Spin,
    Divider,
    DatePicker,
    message,
    Button,
    Tabs,
    Input,
    Upload,
    Icon
} from 'antd';
import locale from "antd/lib/date-picker/locale/zh_CN";
import moment from 'moment';
import {
    prefixFile,
    cfgFileList,
    cfgFileSave,
    cfgFileDelete
} from "../../../fetch/fetchApi";
import classNames from 'classnames';

const TabPane = Tabs.TabPane;
const {
    RangePicker
} = DatePicker;
const startDefaultDate = moment().subtract(7, 'days');
const endDefaultDate = moment();

const filePath = "source/config/platform/";
class ConfigModify extends Component {
    constructor(props) {
        super(props);
        this.init();
        this.state = {
            data: [],
            pagination: {},
            fileList: [],
            selectedRowKeys: []
        }

    }

    init() {
        this.query = {
            page: '1',
            pagecount: '10'
        };
        this.tableColumns = [{
            title: '文件名',
            dataIndex: 'name',
            key: 'name'
        }, {
            title: '上传时间',
            dataIndex: 'createTime',
            key: 'createTime',
			align:'center',
        }, {
            title: '上传人',
            dataIndex: 'createAccount',
            key: 'createAccount',
        }, {
            title: '操作',
            dataIndex: 'operation',
            key: 'operation',
            align:'center',
            render: (text, record) => (
                <div>
                    <a href="javascript:void(0);" onClick={()=>this.handleDownload(record)}>下载</a>
                    <Divider type="vertical" />
                    <a href="javascript:void(0);" onClick={()=>this.handleDelele(record)}>删除</a>
                </div>
            )
        }];
    }

    handleDelele = (record) => {
        cfgFileDelete({
            id: record.id
        }).then((res) => {
            if (res && res.data.code === "200") {
                message.success("删除成功！")
                this.fetch();
            }
        })
    }

    handleDownload = (record) => {
        window.location.href = "https://oms-starcharge-com.oss-cn-qingdao.aliyuncs.com/" + filePath + record.id;
    }


    fetch = (params = {}) => {
        this.setState({
            loading: true
        })
        cfgFileList(this.query).then((res) => {
            if (res && res.data.code === "200") {
                const pagination = this.state.pagination;
                pagination.total = res.data.pageLimit.totalCount;
                pagination.current = parseInt(this.query.page);
                res.data.data.length > 0 && this.props.handle(res.data.data[0]);
                this.setState({
                    data: res.data.data,
                    pagination,
                    selectedRowKeys: res.data.data.length > 0 ? [0] : []
                });
            } else {
                this.setState({
                    data: [],
                    selectedRowKeys: []
                });
            }
            this.setState({
                loading: false,
            })

        });
    }

    componentDidMount() {
        this.setState({
            rangeValue: [startDefaultDate, endDefaultDate]
        })
        this.query.startTime = startDefaultDate.format("YYYY-MM-DD");
        this.query.endTime = endDefaultDate.format("YYYY-MM-DD");
        this.fetch();
    }

    handleTableChange = (pagination, filters, sorter) => {
        this.query.page = pagination.current;
        this.fetch();
    }

    handleChange = (info) => {
        console.log(info);
        let fileList = info.fileList;
        console.log(fileList);
        fileList = fileList.slice(-1);
        if (info.file.status === 'done') {
            const filePath = fileList[0].response.fileIdList[0];
            const arr = filePath.split('/');
            const id = arr[arr.length - 1];
            cfgFileSave({
                id: id,
                name: info.file.name
            }).then((res) => {
                if (res && res.data.code === "200") {
                    message.success(`[${info.file.name}]上传成功 `);
                    this.fetch();
                }

            })

        } else if (info.file.status === 'error') {
            message.error(`[${info.file.name}]上传失败`);
        }
        this.setState({
            fileList
        });
    }

    queryHandler = () => {
        this.fetch();
    }

    handleNameInputChange = (e) => {
        this.query.name = e.target.value;
    }

    handleDateChange = (dates) => {
        const startDate = dates[0];
        const endDate = dates[1];
        if (!startDate || !endDate) {
            this.query.startTime = null;
            this.query.endTime = null;
            this.setState({
                rangeValue: null
            });
            return;
        }
        this.query.startTime = startDate.format("YYYY-MM-DD");
        this.query.endTime = endDate.format("YYYY-MM-DD");
        this.setState({
            rangeValue: dates
        });
    }

    handleConfigBtnClick = () => {
        let excelUrl = prefixFile + '/listExport.do?fileName=平台配置数据&serviceName=platformConfig&searchJson=';
        let paramUrl = '{';
        paramUrl += `"stubId"` + ":" + `"${this.props.stubId}"`
        paramUrl += "}";
        window.location.href = excelUrl + paramUrl;
    }

    handleRadioChange = (selectedRowKeys, selectedRows) => {
        this.props.handle(selectedRows[0]);
        this.setState({
            selectedRowKeys
        })
    }

    render() {
        const rowSelection = {
            type: 'radio',
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: this.handleRadioChange
        }
        const props = {
            accept: '.xls',
            name: 'file',
            action: prefixFile + '/uploadFile.do?storeName=oms_upload&filePath=' + filePath + moment(Date.now()).format("YYYYMMDDHHmmss") + ".xls",
            headers: {
                //authorization: 'authorization-text'
            },
            data: {},
            //showUploadList: false,
            multiple: false,
            beforeUpload(file) {

            },
            onChange: this.handleChange
        };
        const batchModify = <div className="sc-page-content">
            <div className="page-toolbar modal-buttons">
                <Row gutter={8} >
                    <Col lg={8} xl={8} className="whole-fill">
                        <RangePicker format="YYYY-MM-DD" locale={locale} value={this.state.rangeValue} onChange={this.handleDateChange} />
                    </Col>
                    <Col lg={5} xl={5} className="whole-fill">
                        <Input onChange={this.handleNameInputChange} placeholder='文件名称'/>
                    </Col>  
                    <div  className="button-inlineBlock">
                        <Button type="primary" onClick={this.queryHandler}>查询</Button>
                    </div>
                    <div  className="button-inlineBlock">
                        <Button  type="primary" onClick={this.handleConfigBtnClick}>平台配置下载</Button>
                    </div>
                    <div  className="button-inlineBlock">
                        <Upload  {...props} fileList={this.state.fileList}>
                            <Button>
                                <Icon type="upload"/> 上传文件
                            </Button>
                        </Upload>
                    </div>
                </Row>
            </div>

            <div className="page-panel" style={{'marginTop':'30px'}}>
                <Table onChange={this.handleTableChange} bordered rowSelection={rowSelection} dataSource={this.state.data} loading={this.state.loading} columns={this.tableColumns} pagination={this.state.pagination}/>
            </div>

        </div>
        const content =
            <Tabs type="card">
                {/*<TabPane tab="单项修改" key="one">
                    
                </TabPane>*/}
                <TabPane tab="批量修改" key="batch">
                    {batchModify}
                </TabPane>
            </Tabs>
        return content
    }
}
export {
    ConfigModify,
    filePath
};